<template>
  <div class="orders-list">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%">
        <el-table-column prop="id" label="商品id" width="80" align="center" />
        <el-table-column prop="orderNo" label="订单号" width="200" align="center" />
        <el-table-column prop="totalPrice" label="订单金额">
          <template #default="{ row }">
            ¥{{ row.totalPrice.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="state" label="订单状态" width="100"></el-table-column>
        <el-table-column prop="linkUser" label="联系人"  />
        <el-table-column prop="userId" label="下单人id"  />
        <el-table-column prop="createTime" width="180" label="创建时间" />
        <el-table-column prop="linkAddress" label="收货地址" min-width="100" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
              <el-button type="primary" link @click="handleDetail(row)">
                <el-icon><Document /></el-icon>
                详情
              </el-button>
              <!-- <el-button 
                v-if="row.state === 1"
                type="success" 
                link 
                @click="handleShip(row)">
                <el-icon><Van /></el-icon>
                发货
              </el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 发货对话框 -->
    <el-dialog
      v-model="shipDialogVisible"
      title="订单发货"
      width="500px">
      <el-form
        ref="shipFormRef"
        :model="shipForm"
        :rules="shipRules"
        label-width="100px">
        <el-form-item label="物流公司" prop="company">
          <el-select v-model="shipForm.company" placeholder="请选择物流公司">
            <el-option label="顺丰快递" value="SF" />
            <el-option label="中通快递" value="ZTO" />
            <el-option label="圆通快递" value="YTO" />
            <el-option label="韵达快递" value="YD" />
          </el-select>
        </el-form-item>
        <el-form-item label="物流单号" prop="trackingNo">
          <el-input v-model="shipForm.trackingNo" placeholder="请输入物流单号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="shipDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmShip" :loading="shipLoading">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { getOrderListAPI } from '../../../api/order'

const router = useRouter()
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  state: '',
})

// 发货表单
const shipDialogVisible = ref(false)
const shipLoading = ref(false)
const shipFormRef = ref(null)
const currentOrderId = ref(null)
const shipForm = reactive({
  company: '',
  trackingNo: ''
})

const shipRules = {
  company: [
    { required: true, message: '请选择物流公司', trigger: 'change' }
  ],
  trackingNo: [
    { required: true, message: '请输入物流单号', trigger: 'blur' }
  ]
}

// 获取订单列表
const getOrdersList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    }
    // if (searchForm.dateRange?.length === 2) {
    //   params.startDate = searchForm.dateRange[0]
    //   params.endDate = searchForm.dateRange[1]
    // }
    // delete params.dateRange

    // const res = await request({
    //   url: '/order/list',
    //   method: 'get',
    //   params
    // })

    const res = await getOrderListAPI(params)
    console.log(res);
    
    if(res.code !== '200') {
      ElMessage.error(res.msg)
      return
    }
    tableData.value = res.data.records
    total.value = res.data.total
  } catch (error) {
    console.error('获取订单列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getOrdersList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'dateRange' ? [] : ''
  })
  handleSearch()
}

// 查看详情
const handleDetail = (row) => {
  router.push(`/admin/orders/detail/${row.userId}/${row.orderNo}`)
}

// 发货
const handleShip = (row) => {
  currentOrderId.value = row.id
  shipForm.company = ''
  shipForm.trackingNo = ''
  shipDialogVisible.value = true
}

// 确认发货
const confirmShip = () => {
  shipFormRef.value.validate(async (valid) => {
    if (valid) {
      shipLoading.value = true
      try {
        await request({
          url: `/order/ship/${currentOrderId.value}`,
          method: 'put',
          data: shipForm
        })
        ElMessage.success('发货成功')
        shipDialogVisible.value = false
        getOrdersList()
      } catch (error) {
        console.error('发货失败:', error)
      } finally {
        shipLoading.value = false
      }
    }
  })
}


// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getOrdersList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getOrdersList()
}

onMounted(() => {
  getOrdersList()
})
</script>

<style scoped>
.orders-list {
  .search-card {
    margin-bottom: 20px;
  }

  .search-form {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 